﻿using Goway.Log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Goway.StackingUC.SaveFile
{
    public class RWJsonFile
    {
        /// <summary>
        /// 读文件
        /// </summary>
        /// <typeparam name="T">文件内容转换的对象</typeparam>
        /// <param name="filePath">文件路径和文件名</param>
        /// <param name="isMulty">是否为多个对象</param>
        /// <returns></returns>
        public static T ReadJsonFile<T>(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return default(T);
            }

            T result = default(T);
            try
            {
                string[] fileContent = File.ReadAllLines(filePath, Encoding.UTF8);
                if (fileContent != null && fileContent.Count() > 0)
                {
                    string jsonContent = "";
                    foreach (var item in fileContent)
                    {
                        jsonContent += item;
                    }

                    result = JsonToObject<T>(jsonContent);
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"读取Json文件发生异常：{ex.Message}");
                return default(T);
            }

            return result;
        }

        /// <summary>
        /// 读文件
        /// </summary>
        /// <typeparam name="T">文件内容转换的对象</typeparam>
        /// <param name="filePath">文件路径和文件名</param>
        /// <param name="isMulty">是否为多个对象</param>
        /// <returns></returns>
        public static List<T> ReadJsonFileMultyObject<T>(string filePath, bool isMulty = false)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return null;
            }

            List<T> resultList = new List<T>();
            try
            {
                // 读文件
                string[] fileContent = File.ReadAllLines(filePath, Encoding.UTF8);
                if (fileContent != null && fileContent.Count() > 0)
                {
                    // 获取每一个对象
                    foreach (var contentItem in fileContent)
                    {
                        T item = JsonToObject<T>(contentItem);
                        if (item != null)
                        {
                            resultList.Add(item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"读取Json，获取多个对象，发生异常：{ex.Message}");
                return null;
            }

            return resultList;
        }

        /// <summary>
        /// 写 Json 文件
        /// </summary>
        /// <typeparam name="T">数据对象</typeparam>
        /// <param name="filePath">文件路径（不含文件名，以"\"结尾）</param>
        /// <param name="fileName">文件名，含文件后缀，如：set.json</param>
        /// <param name="obj">要写入文件的对象</param>
        /// <param name="isAppend">是否追加，false：不追加，覆盖</param>
        /// <returns>是否正常完成</returns>
        public static bool WriteJsonFile<T>(string filePath, string fileName, T obj, bool isAppend)
        {
            if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName) || obj == null)
            {
                return false;
            }

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string content = string.Empty;
            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                // 写文件
                if (!File.Exists(filePath + fileName))
                {
                    File.Create(filePath + fileName);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    ms.Position = 0;
                    using (StreamReader read = new StreamReader(ms))
                    {
                        content = read.ReadToEnd();
                    }
                }

                if (content.Length == 0)
                {
                    LoggerHelper.Error($"要写入的数据为空，异常退出。");
                    return false;
                }

                using (StreamWriter streamWriter = new StreamWriter(filePath + fileName, isAppend))
                {
                    streamWriter.WriteLine(content);
                    streamWriter.Flush();
                }

                return true;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"保存Json异常：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 写 Json 文件
        /// </summary>
        /// <typeparam name="T">数据对象</typeparam>
        /// <param name="filePath">文件路径（不含文件名，以"\"结尾）</param>
        /// <param name="fileName">文件名，含文件后缀，如：set.json</param>
        /// <param name="obj">要写入文件的对象</param>
        /// <param name="isAppend">是否追加，false：不追加，覆盖</param>
        /// <returns>是否正常完成</returns>
        public static bool WriteJsonFileMulty<T>(string filePath, string fileName, List<T> objList, bool isAppend)
        {
            if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName) || objList == null || objList.Count == 0)
            {
                return false;
            }

            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                if (!File.Exists(filePath + fileName) || !isAppend)
                {
                    File.Create(filePath + fileName);
                }

                using (StreamWriter streamWriter = new StreamWriter(filePath + fileName, isAppend))
                {
                    foreach (var item in objList)
                    {
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                        string content = string.Empty;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            serializer.WriteObject(ms, item);
                            ms.Position = 0;
                            using (StreamReader read = new StreamReader(ms))
                            {
                                content = read.ReadToEnd();
                            }
                        }

                        if (content.Length == 0)
                        {
                            LoggerHelper.Error($"要写入的数据为空，继续下一个对象。");
                            continue;
                        }

                        string fileContent = JsonHelper.JSONSerialize<T>(item);
                        streamWriter.WriteLine(fileContent);
                        streamWriter.Flush();
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"保存Json异常：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Json 文本转为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string jsonText)
        {
            DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            T obj = (T)s.ReadObject(ms);
            ms.Dispose();
            return obj;
        }
    }
}
